import Request from '@/js_sdk/luch-request/luch-request/index.js'
import { GlobalStore } from '@/stores/global.js'
import { showToast } from '@/utils/toast.js'
import { randomString } from '@/utils/index.js'
import md5 from '@/utils/md5.js'

// 请求实例
const http = new Request()

http.setConfig((config) => {
	// config.baseURL = '/api'
	if (process.env.NODE_ENV === 'development') {
		config.baseURL = 'https://test.szchinasun.com'
	} else {
		config.baseURL = 'https://test.szchinasun.com'
		// config.baseURL = 'http://work2.szchinasun.com'
	}
	config.timeout = 32000
	config.header = {
		'Content-Type': 'application/json;charset=UTF-8',
	}
	config.custom = {
		noToken: false,
	}
	return config
})

// 加密函数
export function encryptWithCompany(companyId) {
	const appId = 'client'
	const appKey = 'KHJKH9789FYT67wcd'
	const timestamp = new Date().getTime()
	const nonce = randomString(32)
	const deviceId = uni.getDeviceInfo().deviceId

	const encryptMD5 = `${appId}${appKey}${timestamp}${nonce}${deviceId}${companyId}`

	const sign = md5.hex_md5_32(encryptMD5)

	const encrypt = {
		appId,
		sign,
		timestamp,
		nonce,
		deviceId,
		companyId,
	}

	return encrypt
}

// 请求前拦截
http.interceptors.request.use(async (config) => {
	const gloablStore = GlobalStore()
	let { token, companyId } = gloablStore
	// if (!config.custom.noToken && !token) {
	// 	// token不存在时跳转
	// 	uni.navigateTo({
	// 		url: '/pages/my/my',
	// 	})
	// 	return
	// }
	token = token || 'Basic Y2xpZW50OjEyMw=='
	const encrypt = encryptWithCompany(companyId)
	config.header = {
		...config.header,
		...encrypt,
		Authorization: config.custom.noToken ? config.header.Authorization : token,
	}
	return config
})

// 请求后拦截
http.interceptors.response.use(
	async (response) => {
		return Promise.resolve(response.data)
	},
	async (error) => {
		console.log('-> error', error)
		let { config } = error
		// 请求错误做点什么。可以使用async await 做异步操作
		// uni.showModal({
		// 	title: "错误",
		// 	content: JSON.stringify(error),
		// 	showCancel: false,
		// 	confirmText: "确定"
		// })
		// 请求错误做点什么。可以使用async await 做异步操作
		checkStatus(error.statusCode)
		return Promise.reject(error)
	}
)

export function checkStatus(status) {
	switch (status) {
		case 400:
			showToast('请求失败！请您稍后重试')
			break
		case 401:
			showToast('登录失效！请您重新登录')
			break
		case 403:
			showToast('当前账号无权限访问！')
			break
		case 404:
			showToast('你所访问的资源不存在！')
			break
		case 405:
			showToast('请求方式错误！请您稍后重试')
			break
		case 408:
			showToast('请求超时！请您稍后重试')
			break
		case 500:
			showToast('服务异常！')
			break
		case 502:
			showToast('网关错误！')
			break
		case 503:
			showToast('服务不可用！')
			break
		case 504:
			showToast('网关超时！')
			break
		default:
			showToast(
				error.data?.msg ||
					error.data?.error ||
					error.msg ||
					error.errMsg ||
					'请求失败！'
			)
	}
}

export default http
